package inherit.practice.demo02.ArrayList04;

public class TestCreate {
    public static void main(String[] args) {
        // 任务要求，添加数组，判断id是否重复，判断
        // 创建student对象
        Student[] arr = new Student[3];
        Student stu1 = new Student(1,"小平",18);
        Student stu2 = new Student(2,"小同",19);
//        Student stu3 = new Student(3,"小神",20);
        arr[0] = stu1;
        arr[1] = stu2;
//        arr[2] = stu3;

        Student stu4 = new Student(1,"小河",21);
        // 1.唯一判断 已存在不添加，不存在添加
        boolean flag = contains(arr,stu4.getId());
        if (flag){
            System.out.println("id已存在");
        }else {

           int count =  getCount(arr);
           if(count==arr.length){
               // 2.数组满了
               Student[]  newArr= creatNewArr(arr);
               newArr[count] = stu4;
               printArr(newArr);
           }else {
               // 3.数组未满
               arr[count] = stu4;
               printArr(arr);
           }
        }

    }
    // 判断用户id是否存在
    public static boolean contains(Student[] arr,int id){
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                int sid = stu.getId();
                if(sid == id){
                    return true;
                }
            }
        }
        return false;
    }
    // 判断数组存了几个元素
    public static int getCount(Student[] arr){
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                count++;
            }
        }
        return count;
    }
    // 创建新索引
    public static Student[] creatNewArr(Student[] arr){
        Student[] newArr = new Student[arr.length+1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;
    }

    // 遍历数组
    public static void printArr(Student[] arr){
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu !=null){
                System.out.println(stu.getId()+","+stu.getName()+","+stu.getAge());
            }
            
        }
    }
}
